<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>投稿 - 哔哩哔哩弹幕网</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
      }
    }
    </script>
    <style>
        .upload-container {
            max-width: 800px;
            margin: 2rem auto;
        }
        .video-preview {
            width: 100%;
            max-height: 400px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 1rem;
            display: none;
        }
        .progress {
            height: 25px;
        }
        .drag-area {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 2rem;
            text-align: center;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .drag-area:hover {
            border-color: #0d6efd;
            background: #f1f7ff;
        }
        .drag-area.active {
            border-color: #198754;
            background: #e8f5e9;
        }
        .upload-method-selector {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        .chunk-progress {
            margin-top: 1rem;
        }
        .chunk-status {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .speed-display {
            color: #28a745;
            font-weight: bold;
        }
        .resume-info {
            background: #fff3cd;
            border: 1px solid #ffeeba;
            color: #856404;
            padding: 0.75rem;
            border-radius: 0.375rem;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container">
                <a class="navbar-brand" href="/">
                    <i class="fas fa-play-circle"></i> 哔哩哔哩弹幕网
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav me-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="/"><i class="fas fa-home"></i> 首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/upload.html">
                                <i class="fas fa-upload"></i> 投稿
                            </a>
                        </li>
                    </ul>
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link" href="/profile.html">
                                <i class="fas fa-user"></i> 个人中心
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" @click="handleLogout">
                                <i class="fas fa-sign-out-alt"></i> 退出
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <div v-if="!authLoading && isAuthenticated" id="pageContent">
            <div class="container upload-container">
                <div class="card shadow">
                    <div class="card-body">
                        <h3 class="card-title text-center mb-4">
                            <i class="fas fa-cloud-upload-alt"></i> 上传视频
                        </h3>

                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> 
                            支持格式：MP4、WebM、AVI。最大文件大小：1GB
                        </div>

                        <!-- 上传方式选择器 -->
                        <div class="upload-method-selector">
                            <h5><i class="fas fa-cog"></i> 上传设置</h5>
                            <div class="form-check form-switch">
                                <input class="form-check-input" 
                                       type="checkbox" 
                                       id="enableResume" 
                                       v-model="useChunkedUpload">
                                <label class="form-check-label" for="enableResume">
                                    启用断点续传 
                                    <small class="text-muted">(支持网络中断后继续上传)</small>
                                </label>
                            </div>
                            <div v-if="useChunkedUpload" class="mt-2">
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">分片大小</label>
                                        <select class="form-select form-select-sm" v-model="chunkSize">
                                            <option value="1048576">1MB</option>
                                            <option value="2097152" selected>2MB (推荐)</option>
                                            <option value="5242880">5MB</option>
                                            <option value="10485760">10MB</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">并发数</label>
                                        <select class="form-select form-select-sm" v-model="concurrentUploads">
                                            <option value="1">1个</option>
                                            <option value="2">2个</option>
                                            <option value="3" selected>3个 (推荐)</option>
                                            <option value="5">5个</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 断点续传恢复提示 -->
                        <div v-if="resumeInfo.canResume" class="resume-info">
                            <h6><i class="fas fa-history"></i> 发现未完成的上传</h6>
                            <p>文件："{{ resumeInfo.fileName }}" 已上传 {{ resumeInfo.progress }}%</p>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-warning" @click="resumeUpload">
                                    <i class="fas fa-play"></i> 继续上传
                                </button>
                                <button class="btn btn-outline-danger" @click="clearResume">
                                    <i class="fas fa-trash"></i> 重新开始
                                </button>
                            </div>
                        </div>

                        <form @submit="handleUpload">
                            <div class="drag-area mb-4" 
                                 :class="{ active: isDragActive }"
                                 @click="openFileDialog"
                                 @dragenter="handleDragEnter"
                                 @dragover="handleDragOver"
                                 @dragleave="handleDragLeave"
                                 @drop="handleDrop">
                                <i class="fas fa-cloud-upload-alt fa-3x mb-3"></i>
                                <h4>拖拽或点击选择你要上传的视频</h4>
                                <p>{{ useChunkedUpload ? '支持断点续传，网络中断可继续' : '传统上传模式' }}</p>
                                <div class="supported-formats mt-2">
                                    <i class="fas fa-file-video text-primary" title="MP4"></i>
                                    <i class="fas fa-file-video text-success" title="WebM"></i>
                                    <i class="fas fa-file-video text-info" title="QuickTime"></i>
                                </div>
                                <input type="file" 
                                       ref="fileInput"
                                       @change="handleFileSelect" 
                                       accept="video/*" 
                                       class="d-none" 
                                       required>
                            </div>

                            <video v-if="videoPreview" 
                                   :src="videoPreview" 
                                   class="video-preview mb-4" 
                                   controls
                                   style="display: block;">
                                Your browser does not support the video tag.
                            </video>

                            <div v-if="videoInfo" class="alert alert-info mt-3">
                                <h5><i class="fas fa-info-circle"></i> 文件信息</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <p><strong>文件名:</strong> {{ videoInfo.name }}</p>
                                        <p><strong>文件大小:</strong> {{ videoInfo.size }}</p>
                                    </div>
                                    <div class="col-md-6">
                                        <p><strong>文件类型:</strong> {{ videoInfo.type }}</p>
                                        <p v-if="videoInfo.hash"><strong>文件哈希:</strong> 
                                            <code>{{ videoInfo.hash.substring(0, 16) }}...</code>
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="title" class="form-label">标题</label>
                                <input type="text" 
                                       class="form-control" 
                                       id="title" 
                                       v-model="formData.title"
                                       required
                                       placeholder="请输入视频标题">
                            </div>

                            <div class="mb-3">
                                <label for="description" class="form-label">视频简介</label>
                                <textarea class="form-control" 
                                          id="description" 
                                          v-model="formData.description"
                                          rows="3" 
                                          required
                                          placeholder="请填写视频简介"></textarea>
                            </div>

                            <!-- 上传进度显示 -->
                            <div v-if="uploading" class="mb-3">
                                <label class="form-label">上传进度</label>
                                <div class="progress">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated"
                                         :class="useChunkedUpload ? 'bg-success' : 'bg-primary'"
                                         role="progressbar" 
                                         :style="{ width: uploadProgress + '%' }">
                                        {{ uploadProgress }}%
                                    </div>
                                </div>
                                
                                <!-- 断点续传详细信息 -->
                                <div v-if="useChunkedUpload" class="chunk-progress">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="chunk-status">
                                                <i class="fas fa-layer-group"></i>
                                                分片: {{ chunkStatus.uploaded }}/{{ chunkStatus.total }}
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="chunk-status">
                                                <i class="fas fa-clock"></i>
                                                剩余时间: {{ uploadSpeed.timeRemaining }}
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="speed-display">
                                                <i class="fas fa-tachometer-alt"></i>
                                                {{ uploadSpeed.current }}
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="btn-group mt-2">
                                    <button type="button" 
                                            class="btn btn-danger" 
                                            @click="cancelUpload">
                                        <i class="fas fa-times"></i> 取消上传
                                    </button>
                                    <button v-if="useChunkedUpload && uploadPaused" 
                                            type="button" 
                                            class="btn btn-success" 
                                            @click="resumeCurrentUpload">
                                        <i class="fas fa-play"></i> 继续
                                    </button>
                                    <button v-if="useChunkedUpload && !uploadPaused" 
                                            type="button" 
                                            class="btn btn-warning" 
                                            @click="pauseUpload">
                                        <i class="fas fa-pause"></i> 暂停
                                    </button>
                                </div>
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" 
                                        class="btn btn-primary btn-lg" 
                                        :disabled="uploading || !selectedFile">
                                    <i v-if="uploading" class="fas fa-spinner fa-spin"></i>
                                    <i v-else-if="useChunkedUpload" class="fas fa-layer-group"></i>
                                    <i v-else class="fas fa-upload"></i>
                                    {{ getUploadButtonText() }}
                                </button>
                                <button type="button" 
                                        class="btn btn-outline-secondary" 
                                        @click="goHome">
                                    <i class="fas fa-times"></i> 取消
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="authLoading" id="loadingSpinner" class="text-center mt-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">正在检查登录状态...</p>
        </div>

        <div v-if="!authLoading && !isAuthenticated" class="text-center mt-5">
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i>
                认证检查失败，即将跳转到登录页面...
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script type="module">
        import { createApp, ref, computed, onMounted } from 'vue';
        import { authState, checkAuthStatus, logout, showToast } from '/js/auth.js';

        // MD5计算工具 (简化版)
        const calculateMD5 = async (file) => {
            return new Promise((resolve) => {
                const reader = new FileReader();
                reader.onload = async function(e) {
                    const arrayBuffer = e.target.result;
                    const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
                    const hashArray = Array.from(new Uint8Array(hashBuffer));
                    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
                    resolve(hashHex);
                };
                reader.readAsArrayBuffer(file);
            });
        };

        // 断点续传上传器类
        class ChunkedUploader {
            constructor(file, options = {}) {
                this.file = file;
                this.chunkSize = options.chunkSize || 2 * 1024 * 1024; // 2MB
                this.concurrent = options.concurrent || 3;
                this.onProgress = options.onProgress || (() => {});
                this.onComplete = options.onComplete || (() => {});
                this.onError = options.onError || (() => {});
                this.onSpeedUpdate = options.onSpeedUpdate || (() => {});
                
                this.fileHash = '';
                this.totalChunks = 0;
                this.uploadedChunks = new Set();
                this.uploading = false;
                this.paused = false;
                this.uploadQueue = [];
                this.activeUploads = 0;
                this.uploadedBytes = 0;
                this.startTime = 0;
                this.lastProgressTime = 0;
                this.lastUploadedBytes = 0;
            }

            async initialize(title, description) {
                try {
                    // 计算文件哈希
                    this.fileHash = await calculateMD5(this.file);
                    this.totalChunks = Math.ceil(this.file.size / this.chunkSize);
                    this.title = title;
                    this.description = description;

                    // 检查服务器上的上传状态
                    const statusResponse = await axios.get(`/api/upload/status/${this.fileHash}`);
                    
                    if (statusResponse.data.exists) {
                        if (statusResponse.data.completed) {
                            throw new Error('文件已存在，无需重复上传');
                        }
                        
                        // 恢复已上传的分片
                        this.uploadedChunks = new Set(statusResponse.data.uploadedChunks);
                        this.uploadedBytes = this.uploadedChunks.size * this.chunkSize;
                        
                        console.log(`恢复上传: ${this.uploadedChunks.size}/${this.totalChunks} 分片已上传`);
                    }

                    // 构建待上传队列
                    this.buildUploadQueue();
                    
                    return {
                        canResume: statusResponse.data.exists && !statusResponse.data.completed,
                        progress: statusResponse.data.progress || 0,
                        uploadedChunks: this.uploadedChunks.size,
                        totalChunks: this.totalChunks
                    };

                } catch (error) {
                    console.error('初始化断点续传失败:', error);
                    throw error;
                }
            }

            buildUploadQueue() {
                this.uploadQueue = [];
                for (let i = 0; i < this.totalChunks; i++) {
                    if (!this.uploadedChunks.has(i)) {
                        this.uploadQueue.push(i);
                    }
                }
            }

            async start() {
                if (this.uploading) return;
                
                this.uploading = true;
                this.paused = false;
                this.startTime = Date.now();
                this.lastProgressTime = this.startTime;
                this.lastUploadedBytes = this.uploadedBytes;

                console.log(`开始分片上传: ${this.uploadQueue.length} 个分片待上传`);

                // 启动并发上传
                const uploadPromises = [];
                for (let i = 0; i < Math.min(this.concurrent, this.uploadQueue.length); i++) {
                    uploadPromises.push(this.uploadWorker());
                }

                try {
                    await Promise.all(uploadPromises);
                    
                    if (this.uploadedChunks.size === this.totalChunks) {
                        await this.mergeChunks();
                    }
                } catch (error) {
                    this.uploading = false;
                    this.onError(error);
                }
            }

            async uploadWorker() {
                while (this.uploadQueue.length > 0 && !this.paused) {
                    const chunkIndex = this.uploadQueue.shift();
                    if (chunkIndex === undefined) break;

                    try {
                        this.activeUploads++;
                        await this.uploadChunk(chunkIndex);
                        this.uploadedChunks.add(chunkIndex);
                        this.updateProgress();
                    } catch (error) {
                        // 重新添加到队列末尾重试
                        this.uploadQueue.push(chunkIndex);
                        console.error(`分片 ${chunkIndex} 上传失败，将重试:`, error);
                        
                        // 短暂延迟后重试
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    } finally {
                        this.activeUploads--;
                    }
                }
            }

            async uploadChunk(chunkIndex) {
                const start = chunkIndex * this.chunkSize;
                const end = Math.min(start + this.chunkSize, this.file.size);
                const chunk = this.file.slice(start, end);

                const formData = new FormData();
                formData.append('chunk', chunk);
                formData.append('chunkIndex', chunkIndex);
                formData.append('totalChunks', this.totalChunks);
                formData.append('fileHash', this.fileHash);
                formData.append('fileName', this.file.name);
                formData.append('fileSize', this.file.size);
                formData.append('title', this.title);
                formData.append('description', this.description);

                const response = await axios.post('/api/upload/chunk', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    timeout: 60000 // 60秒超时
                });

                if (!response.data.success) {
                    throw new Error(response.data.error || '分片上传失败');
                }

                this.uploadedBytes += chunk.size;
                console.log(`分片 ${chunkIndex} 上传成功 (${chunk.size} bytes)`);
            }

            async mergeChunks() {
                console.log('所有分片上传完成，开始合并文件...');
                
                const mergeData = {
                    fileHash: this.fileHash,
                    fileName: this.file.name,
                    totalChunks: this.totalChunks,
                    fileSize: this.file.size
                };

                const response = await axios.post('/api/upload/merge', mergeData);
                
                if (response.data.success) {
                    this.uploading = false;
                    this.onComplete(response.data);
                } else {
                    throw new Error(response.data.error || '文件合并失败');
                }
            }

            updateProgress() {
                const progress = Math.round((this.uploadedChunks.size / this.totalChunks) * 100);
                this.onProgress(progress, this.uploadedChunks.size, this.totalChunks);

                // 计算上传速度
                const now = Date.now();
                if (now - this.lastProgressTime > 1000) { // 每秒更新一次速度
                    const timeDiff = (now - this.lastProgressTime) / 1000;
                    const bytesDiff = this.uploadedBytes - this.lastUploadedBytes;
                    const speed = bytesDiff / timeDiff; // bytes per second
                    
                    const remaining = this.file.size - this.uploadedBytes;
                    const timeRemaining = remaining / speed;
                    
                    this.onSpeedUpdate({
                        speed: speed,
                        timeRemaining: timeRemaining
                    });
                    
                    this.lastProgressTime = now;
                    this.lastUploadedBytes = this.uploadedBytes;
                }
            }

            pause() {
                this.paused = true;
                console.log('上传已暂停');
            }

            resume() {
                if (!this.paused) return;
                this.paused = false;
                console.log('上传已恢复');
                
                // 重新启动工作线程
                const uploadPromises = [];
                for (let i = 0; i < Math.min(this.concurrent, this.uploadQueue.length); i++) {
                    uploadPromises.push(this.uploadWorker());
                }
                
                Promise.all(uploadPromises).catch(error => {
                    this.onError(error);
                });
            }

            cancel() {
                this.uploading = false;
                this.paused = true;
                this.uploadQueue = [];
                console.log('上传已取消');
            }
        }

        createApp({
            setup() {
                const authLoading = ref(true);
                const selectedFile = ref(null);
                const videoPreview = ref('');
                const videoInfo = ref(null);
                const isDragActive = ref(false);
                const uploading = ref(false);
                const uploadProgress = ref(0);
                const uploadController = ref(null);
                const uploadPaused = ref(false);
                
                // 断点续传相关状态
                const useChunkedUpload = ref(true);
                const chunkSize = ref(2097152); // 2MB
                const concurrentUploads = ref(3);
                const chunkedUploader = ref(null);
                const chunkStatus = ref({ uploaded: 0, total: 0 });
                const uploadSpeed = ref({ current: '0 KB/s', timeRemaining: '计算中...' });
                const resumeInfo = ref({ canResume: false, fileName: '', progress: 0 });
                
                const formData = ref({
                    title: '',
                    description: ''
                });

                // Auth computed properties
                const isAuthenticated = computed(() => authState.isAuthenticated);
                const currentUser = computed(() => authState.currentUser);

                // Utility functions
                const formatFileSize = (bytes) => {
                    if (bytes === 0) return '0 Bytes';
                    const k = 1024;
                    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                };

                const formatSpeed = (bytesPerSecond) => {
                    return formatFileSize(bytesPerSecond) + '/s';
                };

                const formatTime = (seconds) => {
                    if (!isFinite(seconds) || seconds < 0) return '计算中...';
                    
                    const hours = Math.floor(seconds / 3600);
                    const minutes = Math.floor((seconds % 3600) / 60);
                    const secs = Math.floor(seconds % 60);
                    
                    if (hours > 0) {
                        return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
                    } else {
                        return `${minutes}:${secs.toString().padStart(2, '0')}`;
                    }
                };

                // File handling methods
                const openFileDialog = () => {
                    const fileInput = document.querySelector('input[type="file"]');
                    fileInput.click();
                };

                const handleFileSelect = (event) => {
                    const file = event.target.files[0];
                    processFile(file);
                };

                const processFile = async (file) => {
                    if (!file) return;

                    // Validate file type
                    if (!file.type.startsWith('video/')) {
                        showToast('请选择有效的视频文件', 'error');
                        return;
                    }

                    // Validate file size (1GB max)
                    if (file.size > 1024 * 1024 * 1024) {
                        showToast('视频文件必须小于1GB', 'error');
                        return;
                    }

                    selectedFile.value = file;
                    videoPreview.value = URL.createObjectURL(file);
                    videoInfo.value = {
                        name: file.name,
                        size: formatFileSize(file.size),
                        type: file.type
                    };

                    // Auto-fill title from filename
                    if (!formData.value.title) {
                        formData.value.title = file.name.replace(/\.[^/.]+$/, "");
                    }

                    // 如果启用断点续传，检查是否可以恢复
                    if (useChunkedUpload.value) {
                        try {
                            showToast('正在检查文件状态...', 'info');
                            
                            const uploader = new ChunkedUploader(file, {
                                chunkSize: chunkSize.value,
                                concurrent: concurrentUploads.value
                            });
                            
                            const initResult = await uploader.initialize(
                                formData.value.title,
                                formData.value.description
                            );
                            
                            videoInfo.value.hash = uploader.fileHash;
                            chunkedUploader.value = uploader;
                            
                            if (initResult.canResume) {
                                resumeInfo.value = {
                                    canResume: true,
                                    fileName: file.name,
                                    progress: Math.round(initResult.progress),
                                    uploadedChunks: initResult.uploadedChunks,
                                    totalChunks: initResult.totalChunks
                                };
                                showToast(`发现未完成的上传，已上传 ${initResult.progress.toFixed(1)}%`, 'warning');
                            }
                            
                        } catch (error) {
                            console.error('检查上传状态失败:', error);
                            showToast('检查上传状态失败: ' + error.message, 'error');
                        }
                    }
                };

                // Drag and drop handlers
                const handleDragEnter = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    isDragActive.value = true;
                };

                const handleDragOver = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                };

                const handleDragLeave = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    isDragActive.value = false;
                };

                const handleDrop = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    isDragActive.value = false;
                    
                    const files = e.dataTransfer.files;
                    if (files.length > 0) {
                        processFile(files[0]);
                    }
                };

                // Upload methods
                const handleUpload = async (e) => {
                    e.preventDefault();

                    if (!selectedFile.value) {
                        showToast('请选择视频文件', 'error');
                        return;
                    }

                    if (useChunkedUpload.value) {
                        await handleChunkedUpload();
                    } else {
                        await handleTraditionalUpload();
                    }
                };

                const handleChunkedUpload = async () => {
                    try {
                        uploading.value = true;
                        uploadProgress.value = 0;
                        uploadPaused.value = false;

                        let uploader = chunkedUploader.value;
                        
                        if (!uploader) {
                            uploader = new ChunkedUploader(selectedFile.value, {
                                chunkSize: chunkSize.value,
                                concurrent: concurrentUploads.value,
                                onProgress: (progress, uploaded, total) => {
                                    uploadProgress.value = progress;
                                    chunkStatus.value = { uploaded, total };
                                },
                                onSpeedUpdate: (speed) => {
                                    uploadSpeed.value = {
                                        current: formatSpeed(speed.speed),
                                        timeRemaining: formatTime(speed.timeRemaining)
                                    };
                                },
                                onComplete: (result) => {
                                    uploading.value = false;
                                    showToast('视频上传成功！', 'success');
                                    setTimeout(() => {
                                        window.location.href = `/player.html?id=${result.videoId}`;
                                    }, 1500);
                                },
                                onError: (error) => {
                                    uploading.value = false;
                                    uploadPaused.value = false;
                                    showToast('断点续传失败: ' + error.message, 'error');
                                    console.error('断点续传错误:', error);
                                }
                            });

                            await uploader.initialize(formData.value.title, formData.value.description);
                            chunkedUploader.value = uploader;
                        }

                        await uploader.start();

                    } catch (error) {
                        uploading.value = false;
                        uploadPaused.value = false;
                        showToast('上传失败: ' + error.message, 'error');
                        console.error('断点续传失败:', error);
                    }
                };

                const handleTraditionalUpload = async () => {
                    const uploadFormData = new FormData();
                    uploadFormData.append('file', selectedFile.value);
                    uploadFormData.append('title', formData.value.title);
                    uploadFormData.append('description', formData.value.description);

                    uploadController.value = new AbortController();

                    try {
                        uploading.value = true;
                        uploadProgress.value = 0;

                        const response = await axios.post('/api/videos/upload', uploadFormData, {
                            headers: { 'Content-Type': 'multipart/form-data' },
                            signal: uploadController.value.signal,
                            onUploadProgress: (progressEvent) => {
                                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                                uploadProgress.value = percentCompleted;
                            }
                        });

                        showToast('视频上传成功！', 'success');
                        setTimeout(() => {
                            window.location.href = `/player.html?id=${response.data.id}`;
                        }, 1500);

                    } catch (error) {
                        if (error.name === 'CancelError' || error.name === 'AbortError') {
                            showToast('上传已取消', 'info');
                        } else if (error.response?.status === 401) {
                            showToast('请重新登录', 'error');
                            setTimeout(() => {
                                window.location.href = '/login.html?redirect=/upload.html';
                            }, 1500);
                        } else {
                            showToast(error.response?.data?.message || '上传失败', 'error');
                        }
                        resetUploadState();
                    }
                };

                const cancelUpload = async () => {
                    if (useChunkedUpload.value && chunkedUploader.value) {
                        try {
                            chunkedUploader.value.cancel();
                            
                            // 清理服务器端的上传状态（可选）
                            if (videoInfo.value.hash) {
                                await axios.delete(`/api/upload/cancel/${videoInfo.value.hash}`);
                            }
                        } catch (error) {
                            console.error('取消断点续传失败:', error);
                        }
                    } else if (uploadController.value) {
                        uploadController.value.abort();
                    }
                    
                    resetUploadState();
                    showToast('上传已取消', 'info');
                };

                const pauseUpload = () => {
                    if (chunkedUploader.value) {
                        chunkedUploader.value.pause();
                        uploadPaused.value = true;
                        showToast('上传已暂停', 'info');
                    }
                };

                const resumeCurrentUpload = () => {
                    if (chunkedUploader.value) {
                        chunkedUploader.value.resume();
                        uploadPaused.value = false;
                        showToast('上传已恢复', 'info');
                    }
                };

                const resumeUpload = async () => {
                    if (resumeInfo.value.canResume && chunkedUploader.value) {
                        uploading.value = true;
                        uploadPaused.value = false;
                        resumeInfo.value.canResume = false;
                        
                        chunkStatus.value = {
                            uploaded: resumeInfo.value.uploadedChunks,
                            total: resumeInfo.value.totalChunks
                        };
                        uploadProgress.value = resumeInfo.value.progress;
                        
                        await chunkedUploader.value.start();
                    }
                };

                const clearResume = async () => {
                    try {
                        if (videoInfo.value.hash) {
                            await axios.delete(`/api/upload/cancel/${videoInfo.value.hash}`);
                        }
                        resumeInfo.value.canResume = false;
                        chunkedUploader.value = null;
                        showToast('已清除上传记录，可重新开始', 'info');
                    } catch (error) {
                        console.error('清除上传记录失败:', error);
                        showToast('清除上传记录失败', 'error');
                    }
                };

                const resetUploadState = () => {
                    uploading.value = false;
                    uploadProgress.value = 0;
                    uploadPaused.value = false;
                    uploadController.value = null;
                    chunkStatus.value = { uploaded: 0, total: 0 };
                    uploadSpeed.value = { current: '0 KB/s', timeRemaining: '计算中...' };
                };

                const getUploadButtonText = () => {
                    if (uploading.value) {
                        return uploadPaused.value ? '上传已暂停' : '上传中...';
                    } else if (resumeInfo.value.canResume) {
                        return '继续上传';
                    } else if (useChunkedUpload.value) {
                        return '开始分片上传';
                    } else {
                        return '开始上传';
                    }
                };

                const handleLogout = async (event) => {
                    event.preventDefault();
                    await logout();
                };

                const goHome = () => {
                    window.location.href = '/';
                };

                // Lifecycle
                onMounted(async () => {
                    try {
                        const isAuth = await checkAuthStatus(true);
                        if (!isAuth) {
                            window.location.href = '/login.html?redirect=/upload.html';
                            return;
                        }
                        authLoading.value = false;
                    } catch (error) {
                        console.error('认证检查失败:', error);
                        authLoading.value = false;
                        setTimeout(() => {
                            window.location.href = '/login.html?redirect=/upload.html';
                        }, 2000);
                    }
                });

                return {
                    authLoading,
                    isAuthenticated,
                    currentUser,
                    selectedFile,
                    videoPreview,
                    videoInfo,
                    isDragActive,
                    uploading,
                    uploadProgress,
                    uploadPaused,
                    useChunkedUpload,
                    chunkSize,
                    concurrentUploads,
                    chunkStatus,
                    uploadSpeed,
                    resumeInfo,
                    formData,
                    openFileDialog,
                    handleFileSelect,
                    handleDragEnter,
                    handleDragOver,
                    handleDragLeave,
                    handleDrop,
                    handleUpload,
                    cancelUpload,
                    pauseUpload,
                    resumeCurrentUpload,
                    resumeUpload,
                    clearResume,
                    getUploadButtonText,
                    handleLogout,
                    goHome
                };
            }
        }).mount('#app');
    </script>
</body>
</html>
